import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:sinosheets/main_config.dart';
import 'package:sinosheets/main_logic.dart';
import 'package:sinosheets/pages/base_tab/view.dart';
import 'package:sinosheets/route/app_pages.dart';
import 'package:sinosheets/route/global_binding.dart';
import 'package:sinosheets/route/route_paths.dart';
import 'package:sinosheets/route/route_utils.dart';
import 'package:sinosheets/utils/common_utils/log_util.dart';
import 'package:sinosheets/utils/favorite/product_util.dart';
import 'package:sinosheets/utils/isar_manager.dart';
import 'package:sinosheets/utils/language/language_util.dart';
import 'package:sinosheets/utils/language/translation_service.dart';
import 'package:sinosheets/utils/storage/LSUtil.dart';
import 'package:sinosheets/utils/theme/theme_util.dart';
import 'package:sinosheets/utils/toast_util.dart';
import 'package:sinosheets/utils/turbolink_utils.dart';

// 修复：移除不存在的包导入
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  initApp();
}

void initApp() async {
  ///初始化配置
  await MainConfig.init();

  ///初始化Isar数据库
  await IsarManager().init();

  ///初始化语言包
  final translationService = TranslationService();
  await translationService.init(); // 加载本地语言（en.dart 和 zh.dart）
  await ProductUtil.init();
  runApp(GetMaterialApp(
    home: const App(),
    debugShowCheckedModeBanner: false,
    builder: (context, child) {
      return MediaQuery(
        data: MediaQuery.of(context).copyWith(textScaler: TextScaler.noScaling, boldText: false),
        child: ToastUtil.builder(context, child),
      );
    },
    localizationsDelegates: const [
      GlobalMaterialLocalizations.delegate,
      GlobalWidgetsLocalizations.delegate,
      GlobalCupertinoLocalizations.delegate,
    ],
    supportedLocales: const [
      Locale("zh", "CN"), // 长按显示中文菜单
      Locale("en", "US"),
    ],
    navigatorObservers: [
      ToastUtil.observer,
      GBRouteObserver(),
      routeObserver,
    ],
    initialRoute: RoutePaths.initial,
    initialBinding: GlobalBinding(),
    getPages: AppPages.pages,
    defaultTransition: Transition.rightToLeft,
    locale: Locale(LanguageUtil.getLanguageCode()),
    translations: translationService,
    fallbackLocale: TranslationService.fallbackLocale,
    theme: ThemeData.light(),
    darkTheme: ThemeData.dark(),
    themeMode: ThemeUtil.getThemeMode(),
  ));
}

class App extends StatefulWidget {
  const App({super.key});

  @override
  State<App> createState() => _AppState();
}

class _AppState extends State<App> with WidgetsBindingObserver {
  final MainLogic logic = Get.put(MainLogic());
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);

    /// App启动就更新一次主题
    ThemeUtil.updateTheme();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<MainLogic>(builder: (logic) {
      return FutureBuilder(
          future: null,
          builder: (context, snapshot) {
            return ScreenUtilInit(
              designSize: const Size(375, 812),
              minTextAdapt: true,
              splitScreenMode: true,
              builder: (context, child) {
                double bottomH = MediaQuery.of(context).padding.bottom;
                LSUtil.saveBottomSafeHeight(bottomH);
                return MaterialApp(
                  debugShowCheckedModeBanner: false,
                  // localizationsDelegates: _localization.localizationsDelegates,
                  // supportedLocales: const [
                  //   // 当前应用支持的locale列表
                  //   Locale('zh', 'CN'), // 中文简体
                  //   //其它Locales
                  // ],
                  localizationsDelegates: const [
                    GlobalMaterialLocalizations.delegate,
                    GlobalWidgetsLocalizations.delegate,
                    GlobalCupertinoLocalizations.delegate,
                  ],
                  supportedLocales: const [
                    Locale("zh", "CN"), // 长按显示中文菜单
                    Locale("en", "US"),
                  ],
                  locale: const Locale('zh', 'CN'),
                  navigatorKey: navigatorKey,
                  builder: (context, child) {
                    return MediaQuery(
                      data: MediaQuery.of(context).copyWith(textScaler: TextScaler.noScaling, boldText: false),
                      child: child!,
                    );
                  },
                  home: Scaffold(
                    resizeToAvoidBottomInset: false,
                    body: GestureDetector(
                      onTap: () {
                        FocusScopeNode focusScopeNode = FocusScope.of(context);
                        if (!focusScopeNode.hasPrimaryFocus && focusScopeNode.focusedChild != null) {
                          FocusManager.instance.primaryFocus!.unfocus();
                        }
                      },
                      child: BaseTabPage(),
                    ),
                  ),
                );
              },
            );
          });
    });
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) async {
    super.didChangeAppLifecycleState(state);
    LogUtil.e("=========== AppLifecycleState: ${state.toString()} ==================");
    switch (state) {
      case AppLifecycleState.inactive: // 处于这种状态的应用程序应该假设它们可能在任何时候暂停。
        {
          LogUtil.e('---------- 处于这种状态的应用程序应该假设它们可能在任何时候暂停。 ----------');
        }
        break;
      case AppLifecycleState.resumed: // 应用程序可见，前台
        {
          LogUtil.e('---------- 前台 ----------');

          TurbolinkUtils.checkClipboard();
        }
        break;
      case AppLifecycleState.paused: // 应用程序不可见，后台
        {
          LogUtil.e('---------- 后台 ----------');
        }
        break;
      case AppLifecycleState.detached:
        break;
      case AppLifecycleState.hidden:
        break;
    }
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }
}

final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
final RouteObserver<PageRoute> routeObserver = RouteObserver<PageRoute>();
